package com.ynu.springbootappdemo.controller;

import com.ynu.springbootappdemo.common.utils.BaseResponse;
import com.ynu.springbootappdemo.common.utils.ResultUtils;
import com.ynu.springbootappdemo.model.entity.Categories;
import com.ynu.springbootappdemo.model.vo.CateGoodsVo;
import com.ynu.springbootappdemo.model.vo.GoodsVo;
import com.ynu.springbootappdemo.model.vo.MainCateGoodsVo;
import com.ynu.springbootappdemo.service.CateService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.modelmapper.ModelMapper;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Api(tags = "分类")
@RestController
@RequestMapping("/cate")
public class CateController {

    @Resource
    private ModelMapper modelMapper;

    @Resource
    private CateService service;

    @GetMapping("/getAll")
    @ApiOperation("获取分类数据")
    public BaseResponse<List<CateGoodsVo>> getAll() {
        List<Categories> categories = service.getAll();

        List<CateGoodsVo> cateGoodsVos = new  ArrayList<>();

        categories.forEach(cate -> {
            List<GoodsVo> goodsVos = cate.getCateGoods().stream().map(
                    cateGoods -> modelMapper.map(cateGoods.getGoods(), GoodsVo.class)).collect(Collectors.toList());

            CateGoodsVo map = modelMapper.map(cate, CateGoodsVo.class);
            map.setGoodsVos(goodsVos);
            cateGoodsVos.add(map);
        });



        return ResultUtils.success(cateGoodsVos);

    }

    @GetMapping("/getAllMerged")
    @ApiOperation("获取合并后的分类数据")
    public BaseResponse<List<MainCateGoodsVo>> getAllMerged() {
        List<Categories> categories = service.getAll();  // 获取原始分类数据

        // 合并一级分类
        List<MainCateGoodsVo> mainCateGoodsVos = service.mergeFirstCate(categories);

        //过滤
        List<CateGoodsVo> cateGoodsVos = new  ArrayList<>();
        categories.forEach(cate -> {
            List<GoodsVo> goodsVos = cate.getCateGoods().stream().map(
                    cateGoods -> modelMapper.map(cateGoods.getGoods(), GoodsVo.class)).collect(Collectors.toList());

            CateGoodsVo map = modelMapper.map(cate, CateGoodsVo.class);
            map.setGoodsVos(goodsVos);
            cateGoodsVos.add(map);
        });
        //设置二级商品列表
        return ResultUtils.success(service.mergeSecendCate(cateGoodsVos, mainCateGoodsVos));
    }
}
